﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Text;

namespace Model
{
    /// <summary>
    /// 对内连接
    /// 用于RPC调用
    /// </summary>
    public class NetInnerComponent : NetworkComponent
    {
        /// <summary>
        /// 保存内连接的Session
        /// </summary>
        private Dictionary<string, Session> addressSession = new Dictionary<string, Session>();

        public override void Remove(long id)
        {
            Session session = this.Get(id);

            if (session == null)
                return;

            this.addressSession.Remove(session.RemoteAddress.ToString());

            base.Remove(id);
        }

        /// <summary>
        /// 获取一个内网连接
        /// </summary>
        /// <param name="address"></param>
        /// <returns></returns>
        public Session Get(string address)
        {
            if (this.addressSession.TryGetValue(address, out Session session))
                return session;

            string[] ip = address.Split(":");
            session = this.Create(new IPEndPoint(IPAddress.Parse(ip[0]), int.Parse(ip[1])));
            this.addressSession.Add(address, session);
            return session;
        }

        public Session Get(IPEndPoint iPEndPoint)
        {
            return this.Get(iPEndPoint.ToString());
        }
    }
}
